import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  Checkbox,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  Radio,
  Select,
  Space
} from 'antd';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equInspectionStandardAdd,
  equInspectionStandardGet,
  equInspectionStandardUpdate
} from '@/services/bizApi/shebaodijianbiaozhunjiekou';
import {
  equInfoGetEquipmentCodeList,
  equInfoGetEquipmentNameList
} from '@/services/bizApi/shebaoxinxijiekou';
import { EditableProTable, ProColumns } from '@ant-design/pro-components';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';
import styles from './index.module.scss';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const [checkone, setCheckone] = useState(true);

  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const selctChange = () => {
    const work1UserId = form.getFieldValue('work1UserId');
    const work1Cycle = form.getFieldValue('work1Cycle');
    const work2UserId = form.getFieldValue('work2UserId');
    const work2Cycle = form.getFieldValue('work2Cycle');
    const work3UserId = form.getFieldValue('work3UserId');
    const work3Cycle = form.getFieldValue('work3Cycle');
    if (work1UserId && work1Cycle) {
      setCheckone(false);
    } else if (work2UserId && work2Cycle) {
      setCheckone(false);
    } else if (work3UserId && work3Cycle) {
      setCheckone(false);
    } else {
      setCheckone(true);
    }
  };

  const getEquInspectionStandard = useRequest(
    async (parmas) => {
      const res = await equInspectionStandardGet(parmas);

      form.setFieldsValue({
        ...res?.data,
        dates: dayjs(res?.data?.dates),
        equipmentCode: res?.data?.equipmentCode?.split(',')
      });
      setTimeout(() => {
        setDataSource(
          (res?.data?.detailList?.map((item) => {
            return {
              ...item,
              key: item?.id,
              method1: item?.method1 ? [item?.method1] : undefined,
              method2: item?.method2 ? [item?.method2] : undefined,
              method3: item?.method3 ? [item?.method3] : undefined,
              method4: item?.method4 ? [item?.method4] : undefined,
              method5: item?.method5 ? [item?.method5] : undefined,
              method6: item?.method6 ? [item?.method6] : undefined,
              method7: item?.method7 ? [item?.method7] : undefined,
              method8: item?.method8 ? [item?.method8] : undefined
            };
          }) as unknown as DataSourceType[]) || []
        );
      }, 10);
    },
    {
      manual: true
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加点检详情');
        return;
      }
      const query = {
        ...values,
        dates: values?.dates ? dayjs(values?.dates).format('YYYY-MM-DD') : undefined,
        equipmentCode: values?.equipmentCode?.join(','),
        detailList: dataSource?.map((item: any) => {
          return {
            ...item,
            method1: item?.method1?.[0] ? item?.method1?.[0] : undefined,
            method2: item?.method2?.[0] ? item?.method2?.[0] : undefined,
            method3: item?.method3?.[0] ? item?.method3?.[0] : undefined,
            method4: item?.method4?.[0] ? item?.method4?.[0] : undefined,
            method5: item?.method5?.[0] ? item?.method5?.[0] : undefined,
            method6: item?.method6?.[0] ? item?.method6?.[0] : undefined,
            method7: item?.method7?.[0] ? item?.method7?.[0] : undefined,
            method8: item?.method8?.[0] ? item?.method8?.[0] : undefined
          };
        })
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? equInspectionStandardUpdate(query)
        : equInspectionStandardAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            getEquInspectionStandard.run({ id: arg?.rowData?.id });
          } else {
            form.resetFields();
            form.setFieldsValue({
              dates: dayjs(new Date())
            });
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '部位',
      key: 'part',
      dataIndex: 'part',
      formItemProps: {
        rules: [{ required: true, message: '请输入部位' }]
      },
      width: 100,
      align: 'center'
    },
    {
      title: '图标符号',
      key: 'noInPic',
      dataIndex: 'noInPic',
      valueType: 'digit',
      formItemProps: {
        rules: [{ required: true, message: '请输入图标符号' }]
      },
      width: 100,
      align: 'center'
    },
    {
      title: '点检方法',
      children: [
        {
          title: '目视',
          key: 'method1',
          dataIndex: 'method1',
          formItemProps: {
            rules: [{ required: false, message: '请选择目视' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '手试',
          key: 'method2',
          dataIndex: 'method2',
          formItemProps: {
            rules: [{ required: false, message: '请选择手试' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '耳听',
          key: 'method3',
          dataIndex: 'method3',
          formItemProps: {
            rules: [{ required: false, message: '请选择耳听' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '敲打',
          key: 'method4',
          dataIndex: 'method4',
          formItemProps: {
            rules: [{ required: false, message: '请选择敲打' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '嗅觉',
          key: 'method5',
          dataIndex: 'method5',
          formItemProps: {
            rules: [{ required: false, message: '请选择嗅觉' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '测量',
          key: 'method6',
          dataIndex: 'method6',
          formItemProps: {
            rules: [{ required: false, message: '请选择测量' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '精密',
          key: 'method7',
          dataIndex: 'method7',
          formItemProps: {
            rules: [{ required: false, message: '请选择精密' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        },
        {
          title: '其他',
          key: 'method8',
          dataIndex: 'method8',
          formItemProps: {
            rules: [{ required: false, message: '请选择其他' }]
          },
          renderFormItem: () => {
            return (
              <Checkbox.Group
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          render: (text) => {
            let arr = [];
            if (Array.isArray(text)) {
              arr = text;
            }
            return (
              <Checkbox.Group
                disabled
                value={arr}
                options={[
                  {
                    label: '',
                    value: true
                  }
                ]}
              />
            );
          },
          align: 'center'
        }
      ]
    },
    {
      title: '点检标准',
      key: 'standard',
      dataIndex: 'standard',
      formItemProps: {
        rules: [{ required: true, message: '请输入点检标准' }]
      },
      width: 100,
      align: 'center'
    },
    {
      title: '图例显示',
      key: 'attachment',
      dataIndex: 'attachment',
      formItemProps: {
        rules: [{ required: false, message: '请上传图例显示' }]
      },
      renderFormItem: (_, { record, ...rest }) => {
        return (
          <Upload
            // base64
            //  accept="image/*"
            maxCount={1}
          >
            <Button>上传附件</Button>
          </Upload>
        );
      },
      render: (url) => {
        if (!url || url === '-') return;
        return (
          <Upload
            disabled
            value={url as unknown as string}
            // base64
            //  accept="image/*"
            maxCount={1}
          >
            {/* <Button>上传附件</Button> */}
          </Upload>
        );
      },
      width: 200
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      formItemProps: {
        rules: [{ required: false, message: '请输入备注' }]
      },
      width: 100,
      align: 'center'
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      hidden: args?.type === 'detail',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            if (args?.type === 'detail') return;
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            if (args?.type === 'detail') return;
            setDataSource(dataSource.filter((item) => item.key !== record.key));
          }}
        >
          删除
        </a>
      ]
    }
  ];

  return (
    <Drawer
      title={
        {
          add: '新增点检标准',
          edit: '编辑点检标准',
          detail: '点检标准详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="75%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <ProFormSelect
          name="productionSite"
          label="生产站点"
          placeholder="请选择生产站点"
          rules={[{ required: true, message: '请选择生产站点' }]}
          request={async () => {
            return (store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <ProFormSelect
          name="processSection"
          label="工艺段"
          placeholder="请选择工艺段"
          dependencies={['productionSite']}
          rules={[{ required: true, message: '请选择工艺段' }]}
          request={async () => {
            return (store.dict['processSection'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
          onChange={() => {
            form?.setFieldsValue({
              ...form.getFieldsValue,
              equipmentName: undefined,
              equipmentCode: undefined
            });
          }}
        />
        <ProFormSelect
          name="equipmentName"
          label="设备名称"
          placeholder="请选择设备名称"
          dependencies={['processSection']}
          rules={[{ required: true, message: '请选择设备名称' }]}
          request={async ({ processSection }) => {
            if (!processSection) return [];
            const res = await equInfoGetEquipmentNameList({ processSection });
            return (
              res?.data?.map((item) => {
                return {
                  label: item,
                  value: item
                };
              }) || []
            );
          }}
          onChange={() => {
            form?.setFieldsValue({ ...form.getFieldsValue, equipmentCode: undefined });
          }}
        />
        <ProFormSelect
          name="equipmentCode"
          label="设备编号"
          placeholder="请选择设备编号"
          dependencies={['equipmentName']}
          mode="multiple"
          rules={[{ required: true, message: '请选择设备编号' }]}
          request={async ({ equipmentName }) => {
            if (!equipmentName) return [];
            const res = await equInfoGetEquipmentCodeList({ equipmentName });
            return (
              res?.data?.map((item) => {
                return {
                  label: item,
                  value: item
                };
              }) || []
            );
          }}
        />
        <div className={styles['card']}>
          <div className={styles['card-item']}>
            <div></div>
            <div>点检分工</div>
            <div>点检周期</div>
          </div>
          <div className={styles['card-item']}>
            <div>专工</div>
            <Form.Item
              label=""
              name="work1UserId"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检分工'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检分工"
                showSearch={true}
                optionFilterProp="label"
                onChange={() => {
                  selctChange();
                }}
                options={
                  userInfo?.data?.map((item) => {
                    return {
                      label: item?.fullName,
                      value: item?.id
                    };
                  }) || []
                }
              />
            </Form.Item>
            <Form.Item
              label=""
              name="work1Cycle"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检周期'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检周期"
                onChange={() => {
                  selctChange();
                }}
                options={[
                  {
                    label: 'H',
                    value: 'H'
                  },
                  {
                    label: 'D',
                    value: 'D'
                  },
                  {
                    label: 'W',
                    value: 'W'
                  },
                  {
                    label: 'M',
                    value: 'M'
                  },
                  {
                    label: 'Y',
                    value: 'Y'
                  }
                ]}
              />
            </Form.Item>
          </div>
          <div className={styles['card-item']}>
            <div>维护</div>
            <Form.Item
              label=""
              name="work2UserId"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检分工'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检分工"
                showSearch={true}
                optionFilterProp="label"
                onChange={() => {
                  selctChange();
                }}
                options={
                  userInfo?.data?.map((item) => {
                    return {
                      label: item?.fullName,
                      value: item?.id
                    };
                  }) || []
                }
              />
            </Form.Item>
            <Form.Item
              label=""
              name="work2Cycle"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检周期'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检周期"
                onChange={() => {
                  selctChange();
                }}
                options={[
                  {
                    label: 'H',
                    value: 'H'
                  },
                  {
                    label: 'D',
                    value: 'D'
                  },
                  {
                    label: 'W',
                    value: 'W'
                  },
                  {
                    label: 'M',
                    value: 'M'
                  },
                  {
                    label: 'Y',
                    value: 'Y'
                  }
                ]}
              />
            </Form.Item>
          </div>
          <div className={styles['card-item']}>
            <div>运行</div>
            <Form.Item
              label=""
              name="work3UserId"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检分工'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检分工"
                showSearch={true}
                optionFilterProp="label"
                onChange={() => {
                  selctChange();
                }}
                options={
                  userInfo?.data?.map((item) => {
                    return {
                      label: item?.fullName,
                      value: item?.id
                    };
                  }) || []
                }
              />
            </Form.Item>
            <Form.Item
              label=""
              name="work3Cycle"
              rules={[
                {
                  required: checkone,
                  message: '请选择点检周期'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                allowClear
                placeholder="请选择点检周期"
                onChange={() => {
                  selctChange();
                }}
                options={[
                  {
                    label: 'H',
                    value: 'H'
                  },
                  {
                    label: 'D',
                    value: 'D'
                  },
                  {
                    label: 'W',
                    value: 'W'
                  },
                  {
                    label: 'M',
                    value: 'M'
                  },
                  {
                    label: 'Y',
                    value: 'Y'
                  }
                ]}
              />
            </Form.Item>
          </div>
        </div>
        <Form.Item
          label="编制日期"
          name="dates"
          rules={[
            {
              required: true,
              message: '请选择编制日期'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="请选择编制日期" disabled />
        </Form.Item>
        <EditableProTable<DataSourceType>
          rowKey="key"
          headerTitle=""
          maxLength={20}
          scroll={{
            x: 960
          }}
          recordCreatorProps={{
            position: 'bottom',
            record: () => ({
              key: Date.now()
            })
          }}
          loading={false}
          toolBarRender={() => []}
          columns={columns}
          request={async () => ({
            data: [],
            total: 3,
            success: true
          })}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              console.log(rowKey, data, row);
              // await waitTime(2000);
            },
            onChange: setEditableRowKeys
          }}
        />

        <Form.Item
          label="危险源/防范措施"
          name="dangerTips"
          rules={[
            {
              required: true,
              message: '请输入危险源/防范措施'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入危险源/防范措施" />
        </Form.Item>
        <Form.Item
          label="点巡检标准修订记录"
          name="reviseRecord"
          rules={[
            {
              required: true,
              message: '请输入点巡检标准修订记录'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入点巡检标准修订记录" />
        </Form.Item>
        <Form.Item
          label="是否启用"
          name="enabled"
          rules={[
            {
              required: true,
              message: '请选择是否启用'
            }
          ]}
        >
          <Radio.Group>
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
